<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useUserStore } from '@/stores/userStore'; // 导入用户存储
import axios from 'axios';

const ElMessage = {
  success: (message) => alert(`成功: ${message}`),
  error: (message) => alert(`错误: ${message}`),
  warning: (message) => alert(`警告: ${message}`),
  info: (message) => alert(`信息: ${message}`),
};

const ElMessageBox = {
  confirm: (message) => {
    return new Promise((resolve, reject) => {
      if (window.confirm(message)) {
        resolve();
      } else {
        reject(new Error('用户取消操作')); 
      }
    });
  }
};

const userStore = useUserStore();
const userId = computed(() => userStore.user?.userId || ''); 

const classes = ref([]); 
const courses = ref([]);
const selectedClass = ref(null);
const teacherClasses = ref([]); // 新增：存储当前教师已加入的班级
const allStudentsInSelectedClass = ref([]);

const showClassDialog = ref(false);
const currentClassForm = reactive({
  classesId: '',
  classesName: '',
  courseId: '',
});

const showBulkImportDialog = ref(false);
const studentsToImport = ref([]);
const selectedStudentsForImport = ref([]);

const searchStudentQuery = ref('');

const route = useRoute();

const props = defineProps({
  courseId: {
    type: String,
    required: true,
  },
});

const getClassName = computed(() => (classId) => {
  const cls = classes.value?.find(c => c.classesId === classId);
  return cls ? cls.classesName : '未知班级';
});

const filterableStudentsToImport = computed(() => {
  if (!studentsToImport.value) return [];
  const existingStudentIds = new Set(allStudentsInSelectedClass.value.map(s => s.userId));
  return studentsToImport.value.filter(student => !existingStudentIds.has(student.userId));
});

const filteredStudents = computed(() => {
  if (!searchStudentQuery.value) {
    return filterableStudentsToImport.value;
  }
  const query = searchStudentQuery.value.toLowerCase();
  return filterableStudentsToImport.value.filter(student =>
    student.userId.toLowerCase().includes(query) ||
    student.userName.toLowerCase().includes(query)
  );
});

const selectAllStudents = computed({
  get() {
    return filteredStudents.value.length > 0 && selectedStudentsForImport.value.length === filteredStudents.value.length;
  },
  set(value) {
    if (value) {
      selectedStudentsForImport.value = filteredStudents.value.map(student => student.userId);
    } else {
      selectedStudentsForImport.value = [];
    }
  }
});

const isTeacherInClass = computed(() => (classId) => {
  return teacherClasses.value.some(c => c.classesId === classId);
});

const fetchTeacherClasses = async (userId, courseId) => {
  if (!userId || !courseId) {
    console.warn('获取教师班级列表：用户ID或课程ID缺失。');
    return;
  }
  try {
    const response = await axios.get(`/api/classes/course/${courseId}/teacher/${userId}`);
    teacherClasses.value = response.data || []; // *** 修改点1：从 response.data 获取数据 ***
    console.log(`DEBUG: 教师 ${userId} 在课程 ${courseId} 中的班级:`, teacherClasses.value);
  } catch (error) {
    console.error('获取教师班级列表失败:', error);
  }
};

const fetchClasses = async (courseId) => {
  classes.value = [];

  if (!courseId) {
    console.error('错误：课程ID未通过props获取！无法获取班级列表。');
    ElMessage.error('无法获取课程ID，请确保父组件正确传递了courseId。');
    return; // 直接返回，不进行API调用
  }

  const apiPath = `/api/courses/${courseId}/classes`;
  console.log(`DEBUG: ClassStudentsManagement.vue 准备请求的 API 路径: ${apiPath}`);

  try {
    console.log(`尝试获取课程ID为 ${courseId} 的班级列表...`);
    const response = await axios.get(apiPath);

    console.log('DEBUG: API 响应的原始数据:', response);
    console.log('DEBUG: API 响应中 .data 字段的内容:', response.data);

    classes.value = response.data || []; 
    console.log('班级列表获取成功:', classes.value);
    console.log('DEBUG: 赋值后 classes.value:', classes.value);
    console.log('DEBUG: 赋值后 classes.value 长度:', classes.value?.length);

    const routeClassId = route.params.classId || route.query.classId;
    if (routeClassId && classes.value.some(c => c.classesId === routeClassId)) {
      selectedClass.value = routeClassId;
    } else if (classes.value.length > 0) {
      selectedClass.value = classes.value[0].classesId; 
    } else {
      selectedClass.value = null; 
    }

    if (selectedClass.value) {
      fetchStudentsInClass(selectedClass.value);
    }

    fetchTeacherClasses(userId.value, courseId);

  } catch (error) {
    console.error('获取班级列表失败:', error);
    ElMessage.error('获取班级列表失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    classes.value = [];
  }
};

const fetchCourses = async () => {
  try {
    const response = await axios.get('/api/courses');
    courses.value = response.data || []; // *** 修改点3：从 response.data 获取数据 ***
  } catch (error) {
    console.error('获取课程列表失败:', error);
    ElMessage.error('获取课程列表失败: ' + (error.response?.data?.message || error.message || '未知错误'));
  }
};

const fetchStudentsInClass = async (classId) => {
  if (!classId) {
    allStudentsInSelectedClass.value = [];
    console.log("DEBUG: fetchStudentsInClass 未提供 classId。正在清空学生列表。");
    return;
  }
  console.log(`DEBUG: 尝试获取班级 ID 为 ${classId} 的学生。`);
  try {
    const apiPath = `/api/classes/${classId}/students/ids`;
    console.log(`DEBUG: 从 API 路径请求学生：${apiPath}`);
    const response = await axios.get(apiPath);

    console.log("DEBUG: 学生原始 API 响应:", response);
    
    // 获取学生ID列表后，需要获取学生详细信息
    const studentIds = response.data;
    const students = [];
    for (const studentId of studentIds) {
      try {
        const userRes = await axios.get(`/api/users/${studentId}`);
        students.push(userRes.data);
      } catch (err) {
        console.error(`获取学生信息失败: ${studentId}`, err);
      }
    }
    allStudentsInSelectedClass.value = students;
    console.log(`DEBUG: 班级 ${classId} 的学生已成功获取:`, allStudentsInSelectedClass.value);

  } catch (error) {
    console.error(`获取班级 ${classId} 学生列表失败:`, error);
    ElMessage.error(`获取班级学生列表失败: ${error.response?.data?.message || error.message || '未知错误'}`);
    allStudentsInSelectedClass.value = [];
  }
};

const fetchAllUsersForImport = async () => {
  try {
    const response = await axios.get('/api/users');
    studentsToImport.value = response.data || []; 
    console.log("所有用户已获取:", studentsToImport.value);
  } catch (error) {
    console.error('获取所有用户失败:', error);
    ElMessage.error('获取所有用户失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    studentsToImport.value = [];
  }
};

const handleClassChange = (classItem) => {
  if (classItem) {
    selectedClass.value = classItem.classesId;
    fetchStudentsInClass(classItem.classesId);
  } else {
    selectedClass.value = null;
    allStudentsInSelectedClass.value = [];
  }
};

const openCreateClassDialog = () => {
  Object.assign(currentClassForm, {
    classesId: '',
    classesName: '',
    courseId: props.courseId,
  });
  showClassDialog.value = true;
};

const closeClassDialog = () => {
  showClassDialog.value = false;
};

const saveClass = async () => {
  // 仅检查 classesId, classesName, courseId
  if (!currentClassForm.classesId || !currentClassForm.classesName || !currentClassForm.courseId) {
    ElMessage.error('班级ID、名称和关联课程不能为空！');
    return;
  }

  try {
    const classDataToSave = {
      classesId: currentClassForm.classesId,
      classesName: currentClassForm.classesName,
      course: {
        courseId: currentClassForm.courseId
      }
    };

    await axios.post('/api/classes', classDataToSave);
    ElMessage.success('新班级创建成功！');

    closeClassDialog();
    fetchClasses(props.courseId); 
  } catch (error) {
    console.error('保存班级失败:', error);
    ElMessage.error('保存班级失败: ' + (error.response?.data?.message || error.message || '未知错误'));
  }
};

const deleteClass = async (classId) => {
  try {
    await ElMessageBox.confirm('确定要删除此班级吗？删除后将无法恢复。');
    await axios.delete(`/api/classes/${classId}`);
    ElMessage.success('班级删除成功！');
    fetchClasses(props.courseId); 
  } catch (error) {
    console.error('删除班级失败:', error);
    if (error.message !== '用户取消操作') { 
      ElMessage.error('删除班级失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }
};

const joinClass = async (classId) => {
  if (!userId.value) {
    ElMessage.error('用户ID未获取到，无法加入班级。请确保已登录。');
    return;
  }
  if (isTeacherInClass.value(classId)) {
    ElMessage.warning('您已在此班级中，无需重复加入。');
    return;
  }
  try {
    const apiPath = `/api/classes/${classId}/teachers/${userId.value}`;
    await axios.post(apiPath);
    ElMessage.success('成功加入班级！');
    fetchTeacherClasses(userId.value, props.courseId); 
  } catch (error) {
    console.error('加入班级失败:', error);
    ElMessage.error('加入班级失败: ' + (error.response?.data?.message || error.message || '未知错误'));
  }
};

const exitClass = async (classId) => {
  if (!userId.value) {
    ElMessage.error('用户ID未获取到，无法退出班级。请确保已登录。');
    return;
  }
  if (!isTeacherInClass.value(classId)) {
    ElMessage.warning('您不在当前班级中，无法退出。');
    return;
  }
  try {
    await ElMessageBox.confirm('确定要退出此班级吗？');
    const apiPath = `/api/classes/${classId}/teachers/${userId.value}`;
    await axios.delete(apiPath);
    ElMessage.success('成功退出班级！');
    fetchTeacherClasses(userId.value, props.courseId); 
  } catch (error) {
    console.error('退出班级失败:', error);
    if (error.message !== '用户取消操作') { 
      ElMessage.error('退出班级失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }
};


const addStudentToClass = async (studentId) => {
  if (!selectedClass.value) {
    ElMessage.error('请先选择一个班级！');
    return;
  }
  try {
    await axios.post(`/api/classes/${selectedClass.value}/students/${studentId}`);
    ElMessage.success('学生添加成功！');
    fetchStudentsInClass(selectedClass.value); 
    fetchAllUsersForImport(); 
  } catch (error) {
    console.error('添加学生失败:', error);
    ElMessage.error('添加学生失败: ' + (error.response?.data?.message || error.message || '未知错误'));
  }
};

const removeStudentFromClass = async (studentId) => {
  if (!selectedClass.value) {
    ElMessage.error('请先选择一个班级！');
    return;
  }
  try {
    await ElMessageBox.confirm('确定要从班级中移除此学生吗？');
    await axios.delete(`/api/classes/${selectedClass.value}/students/${studentId}`);
    ElMessage.success('学生移除成功！');
    fetchStudentsInClass(selectedClass.value); 
    fetchAllUsersForImport(); 
  } catch (error) {
    console.error('移除学生失败:', error);
    if (error.message !== '用户取消操作') { 
      ElMessage.error('移除学生失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }
};

const openBulkImportDialog = async () => {
  if (!selectedClass.value) {
    ElMessage.warning('请先选择一个班级，才能进行批量导入操作。');
    return;
  }
  selectedStudentsForImport.value = []; 
  searchStudentQuery.value = ''; 
  await fetchAllUsersForImport(); 
  showBulkImportDialog.value = true;
};

const closeBulkImportDialog = () => {
  showBulkImportDialog.value = false;
  selectedStudentsForImport.value = []; 
};

const bulkAddStudents = async () => {
  if (!selectedClass.value) {
    ElMessage.error('请先选择一个班级！');
    return;
  }
  if (selectedStudentsForImport.value.length === 0) {
    ElMessage.warning('请至少选择一个学生进行导入。');
    return;
  }

  try {
    for (const studentId of selectedStudentsForImport.value) {
      await axios.post(`/api/classes/${selectedClass.value}/students/${studentId}`);
    }
    ElMessage.success(`成功导入 ${selectedStudentsForImport.value.length} 名学生！`);
    closeBulkImportDialog();
    fetchStudentsInClass(selectedClass.value); 
  } catch (error) {
    console.error('批量添加学生失败:', error);
    ElMessage.error('批量添加学生失败: ' + (error.response?.data?.message || error.message || '未知错误'));
  }
};

onMounted(() => {
  if (props.courseId) {
    fetchCourses();
    fetchClasses(props.courseId);
    fetchTeacherClasses(userId.value, props.courseId);
  } else {
    ElMessage.error('未检测到课程ID，请确保父组件通过props正确传递了courseId。');
  }
});

watch(() => props.courseId, (newCourseId) => {
  if (newCourseId) {
    fetchClasses(newCourseId);
    fetchTeacherClasses(userId.value, newCourseId);
  }
});

watch(() => route.params.classId, (newClassId) => {
  if (newClassId && classes.value && classes.value.some(c => c.classesId === newClassId)) {
    selectedClass.value = newClassId;
    fetchStudentsInClass(newClassId);
  } else if (!newClassId && classes.value?.length > 0) {
    selectedClass.value = classes.value[0].classesId;
    fetchStudentsInClass(classes.value[0].classesId);
  } else {
    selectedClass.value = null;
    allStudentsInSelectedClass.value = [];
  }

  fetchTeacherClasses(userId.value, props.courseId);
}, { immediate: true });
</script>

<template>
  <div class="class-students-management-page container-fluid">
    <h1 class="h2 page-title">
      班级学生管理
    </h1>

    <div class="row justify-content-center">
      <div class="col-lg-10 col-md-12">
        <div class="card shadow-sm data-card">
          <div class="card-header d-flex align-items-center justify-content-between">
            <h5 class="mb-0">
              班级列表
            </h5>
            <div class="header-actions">
              <button
                class="btn btn-sm btn-success me-2"
                @click="openCreateClassDialog"
              >
                <i class="bi bi-plus-lg me-1" /> 新建班级
              </button>
            </div>
          </div>
          <div class="card-body p-4">
            <div
              v-if="classes.length === 0"
              class="alert alert-info text-center"
              role="alert"
            >
              暂无班级信息，请创建新班级。
            </div>
            <ul
              v-else
              class="list-group class-list"
            >
              <li
                v-for="classItem in classes"
                :key="classItem.classesId"
                class="list-group-item d-flex justify-content-between align-items-center class-item"
                :class="{ 'active': selectedClass === classItem.classesId }"
                @click="handleClassChange(classItem)"
              >
                <div>
                  <span class="class-name">{{ classItem.classesName }}</span>
                  <small class="ms-2 class-id-display">ID: {{ classItem.classesId }}</small>
                </div>
                <div class="class-actions">
                  <button
                    v-if="!isTeacherInClass(classItem.classesId)"
                    class="btn btn-sm btn-primary me-2"
                    @click.stop="joinClass(classItem.classesId)"
                  >
                    <i class="bi bi-person-plus-fill me-1" /> 加入班级
                  </button>
                  <button
                    v-else
                    class="btn btn-sm btn-secondary me-2"
                    @click.stop="exitClass(classItem.classesId)"
                  >
                    <i class="bi bi-person-dash-fill me-1" /> 退出班级
                  </button>
                  <button
                    class="btn btn-sm btn-danger"
                    @click.stop="deleteClass(classItem.classesId)"
                  >
                    <i class="bi bi-trash me-1" /> 删除
                  </button>
                </div>
              </li>
            </ul>
          </div>
        </div>

        <div
          v-if="selectedClass"
          class="card shadow-sm data-card mt-4"
        >
          <div class="card-header d-flex align-items-center justify-content-between">
            <h5 class="mb-0">
              班级学生列表 - {{ getClassName(selectedClass) }}
            </h5>
            <div class="student-actions">
              <button
                class="btn btn-sm btn-primary"
                @click="openBulkImportDialog"
              >
                <i class="bi bi-person-fill-add me-1" /> 批量导入学生
              </button>
            </div>
          </div>
          <div class="card-body p-4">
            <div
              v-if="allStudentsInSelectedClass.length === 0"
              class="alert alert-warning text-center"
              role="alert"
            >
              当前班级暂无学生。
            </div>
            <div
              v-else
              class="table-responsive"
            >
              <table class="table table-hover student-table">
                <thead>
                  <tr>
                    <th>学号</th>
                    <th>姓名</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="student in allStudentsInSelectedClass"
                    :key="student.userId"
                  >
                    <td class="student-id-col">
                      {{ student.userId }}
                    </td>
                    <td class="student-name-col">
                      {{ student.userName }}
                    </td>
                    <td class="student-actions-col">
                      <button
                        class="btn btn-sm btn-danger"
                        @click="removeStudentFromClass(student.userId)"
                      >
                        <i class="bi bi-person-dash-fill me-1" /> 移除
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div
      v-if="showClassDialog"
      class="modal-overlay"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              新建班级
            </h5>
            <button
              type="button"
              class="btn-close"
              @click="closeClassDialog"
            />
          </div>
          <div class="modal-body">
            <form @submit.prevent="saveClass">
              <div class="mb-3">
                <label
                  for="classesId"
                  class="form-label"
                >班级ID：</label>
                <input
                  id="classesId"
                  v-model="currentClassForm.classesId"
                  type="text"
                  class="form-control"
                  required
                >
              </div>

              <div class="mb-3">
                <label
                  for="className"
                  class="form-label"
                >班级名称：</label>
                <input
                  id="className"
                  v-model="currentClassForm.classesName"
                  type="text"
                  class="form-control"
                  required
                >
              </div>
              <div class="mb-3">
                <label
                  for="courseSelect"
                  class="form-label"
                >关联课程：</label>
                <input
                  id="courseSelect"
                  type="text"
                  class="form-control"
                  :value="props.courseId"
                  disabled
                >
              </div>
              <div class="d-flex justify-content-end mt-4">
                <button
                  type="submit"
                  class="btn btn-primary me-2"
                >
                  创建
                </button>
                <button
                  type="button"
                  class="btn btn-secondary"
                  @click="closeClassDialog"
                >
                  取消
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <div
      v-if="showBulkImportDialog"
      class="modal-overlay"
    >
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              批量导入学生到 - {{ getClassName(selectedClass) }}
            </h5>
            <button
              type="button"
              class="btn-close"
              @click="closeBulkImportDialog"
            />
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label
                for="studentSearchFilter"
                class="form-label"
              >搜索学生（学号或姓名）：</label>
              <input
                id="studentSearchFilter"
                v-model="searchStudentQuery"
                type="text"
                class="form-control"
                placeholder="输入学号或姓名过滤"
              >
            </div>

            <div
              v-if="filteredStudents.length > 0"
              class="student-import-list mb-3"
              style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 0.5rem;"
            >
              <table class="table table-striped table-hover mb-0">
                <thead>
                  <tr>
                    <th style="width: 50px;">
                      <input
                        v-model="selectAllStudents"
                        type="checkbox"
                      >
                    </th>
                    <th>学号</th>
                    <th>姓名</th>
                    <th>角色ID</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="student in filteredStudents"
                    :key="student.userId"
                  >
                    <td>
                      <input
                        v-model="selectedStudentsForImport"
                        type="checkbox"
                        :value="student.userId"
                      >
                    </td>
                    <td>{{ student.userId }}</td>
                    <td>{{ student.userName }}</td>
                    <td>{{ student.roleId }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div
              v-else
              class="alert alert-info text-center"
            >
              暂无符合条件的学生可导入。
            </div>

            <div class="d-flex justify-content-end mt-4">
              <button
                type="button"
                class="btn btn-primary me-2"
                :disabled="selectedStudentsForImport.length === 0"
                @click="bulkAddStudents"
              >
                <i class="bi bi-person-fill-add me-1" /> 确认导入 ({{ selectedStudentsForImport.length }})
              </button>
              <button
                type="button"
                class="btn btn-secondary"
                @click="closeBulkImportDialog"
              >
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import '../../assets/css/theme.css';

.class-students-management-page {
  padding: 1.5rem;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 1.5rem;
  color: #333;
}

.data-card {
  border: none;
  border-radius: 0.75rem;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  background-color: #ffffff;
}

.card-header {
  border-bottom: none;
  padding: 1.25rem 1.5rem;
  background-color: var(--primary);
  color: white;
  font-size: 1.1rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-top-left-radius: 0.75rem;
  border-top-right-radius: 0.75rem;
}

.card-body {
  padding: 1.5rem;
}

.class-list {
  max-height: 400px;
  overflow-y: auto;
  border-radius: 0.5rem;
  border: 1px solid #e0e0e0; 
}

.class-item {
  cursor: pointer;
  padding: 1rem 1.25rem;
  border-left: 5px solid transparent; 
  transition: all 0.2s ease-in-out;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08); 
}

.class-item:last-child {
  border-bottom: none; 
}

.class-item:hover {
  background-color: #e9ecef;
}

.class-item.active {
  background-color: var(--primary-light); 
  border-color: var(--primary); 
  color: var(--primary-dark);
  font-weight: 500;
}

.class-item.active .class-name,
.class-item.active .class-id-display { 
  color: var(--primary-dark); 
}

.class-name {
  font-size: 1.1rem;
  font-weight: 500;
}

.class-id-display {
  color: #333; 
  font-size: 1.1rem; 
  font-weight: 500; 
  white-space: nowrap; 
}


.student-table {
  width: 100%;
  margin-bottom: 0; 
  border-collapse: separate;
  border-spacing: 0 0.5rem; 
}

.student-table thead th {
  background-color: #f2f2f2;
  border-bottom: 2px solid var(--primary);
  padding: 1rem;
  font-weight: 600;
  color: #555;
  text-align: left;
  vertical-align: middle; 
}

.student-table tbody tr {
  background-color: #fdfdfd;
  border-radius: 0.5rem;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.02);
  transition: all 0.2s ease-in-out;
}

.student-table tbody tr:hover {
  background-color: #eef;
  transform: translateY(-2px);
  box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.05);
}

.student-table tbody td {
  padding: 1rem;
  vertical-align: middle; 
  border-top: none; 
}

.student-table th:nth-child(1), .student-table td.student-id-col {
  width: 25%; 
  text-align: left;
}

.student-table th:nth-child(2), .student-table td.student-name-col {
  width: 35%; 
  text-align: left;
}

.student-table th:nth-child(3), .student-table td.student-actions-col {
  width: 40%; 
  text-align: right; 
}


.btn {
  min-width: 80px; /* 表格操作的最小宽度 */
  font-size: 0.85rem;
  padding: 0.5rem 0.9rem;
  border-radius: 0.3rem;
  transition: all 0.2s ease-in-out;
}

.btn-primary {
  background-color: var(--primary);
  border-color: var(--primary);
}

.btn-primary:hover {
  background-color: var(--primary-dark);
  border-color: var(--primary-dark);
}

.btn-success {
  background-color: var(--success);
  border-color: var(--success);
}

.btn-success:hover {
  background-color: var(--success-dark);
  border-color: var(--success-dark);
}

.btn-info {
  background-color: var(--info);
  border-color: var(--info);
  color: white;
}

.btn-info:hover {
  background-color: var(--info-dark);
  border-color: var(--info-dark);
}

.btn-danger {
  background-color: var(--danger);
  border-color: var(--danger);
}

.btn-danger:hover {
  background-color: var(--danger-dark);
  border-color: var(--danger-dark);
}

.btn-secondary {
  background-color: var(--gray);
  border-color: var(--gray);
  color: white;
}

.btn-secondary:hover {
  background-color: var(--gray-dark);
  border-color: var(--gray-dark);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1050; /* Bootstrap modal-backdrop z-index */
}

.modal-dialog {
  background: white;
  border-radius: 0.75rem;
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
  max-width: 500px;
  width: 90%;
  animation: fadeIn 0.3s ease-out;
}

.modal-dialog.modal-lg {
  max-width: 800px;
}

.modal-content {
  border: none;
  border-radius: 0.75rem;
  overflow: hidden; 
}

.modal-header {
  background-color: var(--primary);
  color: white;
  padding: 1.25rem 1.5rem;
  border-bottom: none; 
}

.modal-title {
  font-size: 1.25rem;
  font-weight: 600;
}

.btn-close {
  filter: invert(1); 
}

.modal-body {
  padding: 1.5rem;
}

.student-search-results, .student-import-list {
  border: 1px solid #e0e0e0;
  border-radius: 0.5rem;
}

.student-search-results .list-group-item,
.student-import-list .table tbody tr td {
  padding: 0.75rem 1.25rem;
  border-left: none;
  border-right: none;
  border-top: none;
}

.student-search-results .list-group-item:last-child {
  border-bottom: none;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
  .class-item {
    flex-direction: column;
    align-items: flex-start;
  }
  .class-actions {
    margin-top: 0.5rem;
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  .class-id-display {
      display: block; 
      font-size: 0.95em; 
      margin-left: 0 !important; 
      margin-top: 0.2rem; 
  }

  .student-table thead {
    display: none; 
  }
  .student-table tbody, .student-table tr, .student-table td {
    display: block; 
    width: 100%;
  }
  .student-table tbody tr {
    margin-bottom: 1rem;
    border: 1px solid #e0e0e0;
  }
  .student-table td {
    text-align: right;
    display: flex; 
    justify-content: space-between; 
    align-items: center; 
    padding-right: 10px; 
    padding-left: 10px; 
  }

  .student-table td::before {
    content: attr(data-label);
    position: static;
    width: auto;
    text-align: left;
    font-weight: 600;
    flex-shrink: 0; 
    margin-right: 10px; 
  }
  
  .student-table td:nth-of-type(1)::before { content: "学号:"; }
  .student-table td:nth-of-type(2)::before { content: "姓名:"; }
  .student-table td:nth-of-type(3)::before { content: "操作:"; }
}
</style>
